import java.net.*;
import java.io.*;
import java.util.*;
import nanoxml.XMLElement;

/**
 *
 * @author marduke
 * * basado en: http://zerioh.tripod.com/ressources/sockets.html
 */
public class ClienteNodo {

    Socket requestSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    String messageToServer;
    int puerto = 1800;
    String host;
    Vector vecinos = new Vector();
    

    public ClienteNodo() {
    }

    public ClienteNodo(String mensaje, String host) {
        this.host = host;
        this.messageToServer = mensaje;
        this.vecinos = vecinos;
        
    }

    String run() {
        String retorno = new String();
        try {
            //1. creating a socket to connect to the server
            requestSocket = new Socket(host, 1800);
            System.out.println("Connected to server");
            //2. get Input and Output streams
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());
            //3: Communicating with the server
            do {
                try {

                    message = (String) in.readObject();

                    
                    sendMessage(messageToServer);

                    

                    //Deberia recibir si es alcanze el xml pasado a string de
                    //los ip alcanzables.
                    message = (String) in.readObject();
                    

                    if (message.compareTo("Error") == 0) {
                        System.out.println("Se produjo un error.");
                    } else if (message.equals("Recibe")) {
                        String menarchivo = (String) in.readObject();
                        recibirArchivo(requestSocket, menarchivo);
                    }  else{
                        retorno = message;
                    }
                    
                    

                    message = "bye";

                    sendMessage(message);

                } catch (ClassNotFoundException classNot) {
                    System.err.println("data received in unknown format");
                    
                }
            } while (!message.equals("bye"));
        } catch (UnknownHostException unknownHost) {
            System.err.println("El servidor no esta activado, o el ip no es el correcto.!");
//        } catch (ConnectException connectException) {
//            System.err.println("Estas tratando de conectarte a un puerto malo!");
//            System.exit(-2);
//        }
        } catch (ConnectException conE)  {
                    System.err.println("No existe ese nodo, el cual esta especificado en el archivo de maquinas");
                    return "Error";

                } 

        catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            //4: Closing connection
            try {
                in.close();
                out.close();
                requestSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

        return retorno;
    }
    
    void sendMessage(String msg) {
        try {
            out.writeObject(msg);
            out.flush();
           
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    private void recibirArchivo(Socket sock, String nomArchivo) {
        try {
    int filesize=20000000; // filesize temporary hardcoded

    long start = System.currentTimeMillis();
    int bytesRead;
    int current = 0;
    // localhost for testing
//    Socket sock = new Socket(maquina,13267);
    System.out.println("Connecting...");

    // receive file
    byte [] mybytearray  = new byte [filesize];
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream(nomArchivo);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    bytesRead = is.read(mybytearray,0,mybytearray.length);
    current = bytesRead;

    // thanks to A. Cádiz for the bug fix
    do {
       bytesRead =
          is.read(mybytearray, current, (mybytearray.length-current));
       if(bytesRead >= 0) current += bytesRead;
    } while(bytesRead > -1);

    bos.write(mybytearray, 0 , current);
    bos.flush();
    long end = System.currentTimeMillis();
    System.out.println(end-start);
    bos.close();
    sock.close();
        }catch(Exception e) {}
    }
}
